<template>
  <section class="container">
    <FormItem
      :form-items="formItem"
      @enter-key="handleQuery"
      @button-click="handleButtonClick"
    />
    <Table
      @handleClick="handleClick"
      :columns="tableColumns"
      @handleChange="handleChange"
      :total="total"
      :data="data"
    />
  </section>
</template>

<script lang="ts" setup>
import FormItem from "~/components/FormItem.vue";
import Table from "~/components/Table.vue";
import { contact as formdata, contactColumns as tableColumns } from "./data";
import { list, remove } from "~/api/contacts";
import { showNotification } from "~/services/notificationService";
import { ElMessage, ElMessageBox } from "element-plus";
const options = ref<any[]>([]);
const formItem = ref<any>([]);
const data = ref<any[]>([]);
const total = ref<any>(null);

const fetchData = async (v: any = {}) => {
  try {
    v.type = 'dihaiba'
    const response = await list(v); // 替换为你的 API 地址
    data.value = response.data.data;
    total.value = response.data.total;
  } catch (error) {
    showNotification(error);
  }
};

onMounted(async () => {
  formItem.value = formdata(options);
  await fetchData(); // 调用数据请求方法
});

const handleClick = async (btn: string, row: any) => {
  switch (btn) {
    case "编辑":
      // 处理编辑操作
      break;
    case "删除":
      // 处理删除操作
      ElMessageBox.confirm("是否删除该条数据？", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(async () => {
          const res = await remove({ _id: row._id }); // 替换为你的 API 地址
          if (res.code === 200) {
            showNotification("删除成功", "success");
            // 删除成功，刷新数据
            await fetchData();
          } else {
            // 删除失败，显示错误信息
            showNotification(res.msg, "error");
          }
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "已取消删除",
          });
        });

      break;
    default:
      break;
  }
};

const handleQuery = async (v: any) => {
  await fetchData(v); // 调用数据请求方法
};

const handleChange = async (v: any) => {

  await fetchData({ pageIndex: v }); // 调用数据请求方法
};

const handleButtonClick = async (type: string, params: any, formEL: any) => {
  switch (type) {
    case "搜索":
      await fetchData(params); // 调用数据请求方法
      break;
    case "重置":
      formEL.resetFields()
      break;
  }
};
</script>

<style scoped lang="stylus">
.container {
  padding: 20px;
}
</style>
